package com.temperate;

import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author:wesley
 */
public class TempMapper extends Mapper<Text,Text,TempKey, DoubleWritable> {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void map(Text key, Text value, Context context) throws IOException, InterruptedException {

        try {
            Date date = sdf.parse(key.toString());

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(calendar.MONDAY) + 1;

            String valStr = value.toString();
            double temperate = Double.parseDouble(valStr.substring(0,valStr.lastIndexOf("c")));

            TempKey tempKey = new TempKey();
            tempKey.setYear(year);
            tempKey.setMonth(month);
            tempKey.setTemperate(temperate);
            context.write(tempKey, new DoubleWritable(temperate));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}
